package com.yaolonga.dc.core;

import com.yaolonga.dc.core.exception.ExecutorSpiLoadException;
import com.yaolonga.dc.core.exception.NodeExecuteException;
import com.yaolonga.dc.core.spi.NodeExecutor;

import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;

/**
 * @Author: yaolong
 * @CreateTime: 2024-10-20  19:15
 * @Description: DcExecutorManager
 * @Version: 1.0
 */
public class DcExecutorManager {

   private static final  Map<String, NodeExecutor<?>> executorMap = new ConcurrentHashMap<>();

    //   spi
    static {
        try {
            ServiceLoader<NodeExecutor> _providers = ServiceLoader.load(NodeExecutor.class);
            for (NodeExecutor executor : _providers) {
                executorMap.put(executor.getExecutorType().getId().toLowerCase(), executor);
            }
        }catch (Exception e){
            throw new ExecutorSpiLoadException("加载脚本执行器失败：" + e.getMessage(),e);
        }
    }


    public static NodeExecutor<?> getExecutor(String type){
        NodeExecutor<?> nodeExecutor = executorMap.get(type);
        if (nodeExecutor == null){
            throw new NodeExecuteException("未找到对应的dc执行器：" + type);
        }
        return nodeExecutor;
    }

    public static NodeExecutor<?> getExecutor(ExecutorType type){
        return getExecutor(type.getId());
    }
}
